import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Image, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber,
  message,
  Upload,
  Tabs
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined 
} from '@ant-design/icons';
import request from '../../utils/request';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import useAuthStore from '../../stores/authStore';

const { TextArea } = Input;
const { Option } = Select;

const timeTypeOptions = [
  { label: '周末', value: 'weekend' },
  { label: '工作日', value: 'weekday' },
  { label: '晚上', value: 'evening' },
];

const editorStyle = {
  height: '200px',
  width: '100%'
};

const customStyles = `
  .quill {
    width: 100%;
  }
  .ql-container {
    min-height: 200px;
    font-size: 14px;
    border: 1px solid #d9d9d9;
    border-radius: 0 0 4px 4px;
  }
  .ql-toolbar {
    border: 1px solid #d9d9d9;
    border-radius: 4px 4px 0 0;
    border-bottom: none;
  }
  .ql-editor {
    min-height: 200px;
    padding: 12px 15px;
    line-height: 1.5;
  }
`;

const Courses = () => {
  const [loading, setLoading] = useState(false);
  const [courses, setCourses] = useState([]);
  const [categories, setCategories] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentCourse, setCurrentCourse] = useState(null);
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [schedules, setSchedules] = useState([]);
  const { user } = useAuthStore();

  useEffect(() => {
    const styleElement = document.createElement('style');
    styleElement.innerHTML = customStyles;
    document.head.appendChild(styleElement);

    return () => {
      document.head.removeChild(styleElement);
    };
  }, []);

  // 获取课程列表
  const fetchCourses = async () => {
    try {
      if (!user?.id) {
        message.error('未获取到教师信息');
        return;
      }
      setLoading(true);
      const res = await request.get('/api/admin/courses', {
        params: {
          teacherId: user.id
        }
      });
      if (res.code === 0) {
        setCourses(res.data);
      }
    } catch (error) {
      message.error('获取课程列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const res = await request.get('/api/admin/categories');
      if (res.code === 0) {
        setCategories(res.data);
      }
    } catch (error) {
      message.error('获取分类列表失败');
    }
  };

  // 获取课程章节
  const fetchSchedules = async (courseId) => {
    try {
      const res = await request.get(`/api/admin/courses/${courseId}/schedules`);
      if (res.code === 0) {
        setSchedules(res.data);
      }
    } catch (error) {
      message.error('获取课程章节失败');
    }
  };

  // 表格列配置
  const columns = [
    {
      title: '课程封面',
      dataIndex: 'image_url',
      width: 120,
      render: (url) => (
        <Image
          src={url}
          alt="课程封面"
          width={100}
          height={60}
          style={{ objectFit: 'cover' }}
          preview={{
            maskClassName: 'customize-mask',
            mask: <div>点击预览</div>
          }}
        />
      )
    },
    {
      title: '课程名称',
      dataIndex: 'title',
      width: 200,
    },
    {
      title: '分类',
      dataIndex: 'category_id',
      width: 120,
      render: (categoryId) => {
        const category = categories.find(c => c.id === categoryId);
        return category?.name || '-';
      }
    },
    {
      title: '标签',
      dataIndex: 'tags',
      width: 200,
      render: (tags) => (
        <Space wrap>
          {tags?.split(',').map(tag => (
            <Tag color="processing" key={tag}>{tag}</Tag>
          ))}
        </Space>
      )
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 100,
      render: (price) => `¥${price}`
    },
    {
      title: '上课时间',
      dataIndex: 'time_type',
      width: 100,
      render: (timeType) => {
        const option = timeTypeOptions.find(o => o.value === timeType);
        return option?.label || '-';
      }
    },
    {
      title: '报名人数',
      dataIndex: 'enroll_count',
      width: 100,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 180,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="primary"
            size="default"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            danger
            size="default"
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  useEffect(() => {
    if (user?.id) {
      fetchCourses();
      fetchCategories();
    }
  }, [user]);

  // 处理编辑
  const handleEdit = async (record) => {
    setCurrentCourse(record);
    form.setFieldsValue({
      ...record,
      tags: record.tags?.split(','),
      image_url: record.image_url?.split('?')[0]
    });
    
    if (record.image_url) {
      setFileList([{
        uid: '-1',
        name: 'course.jpg',
        status: 'done',
        url: record.image_url
      }]);
    } else {
      setFileList([]);
    }
    
    // 获取课程章节
    await fetchSchedules(record.id);
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个课程吗？删除后无法恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await request.delete(`/api/admin/courses/${id}`, {
            params: {
              teacherId: user.id
            }
          });
          if (res.code === 0) {
            message.success('删除成功');
            fetchCourses();
          } else {
            message.error(res.msg || '删除失败');
          }
        } catch (error) {
          message.error('删除失败');
        }
      }
    });
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      if (!user?.id) {
        message.error('未获取到教师信息');
        return;
      }

      if (!values.image_url && !currentCourse) {
        message.error('请上传课程封面');
        return;
      }

      const data = {
        ...values,
        tags: Array.isArray(values.tags) ? values.tags.join(',') : values.tags,
        teacher_id: user.id
      };

      let res;
      if (currentCourse) {
        // 编辑课程时确保是当前教师的课程
        if (currentCourse.teacher_id !== user.id) {
          message.error('无权修改其他教师的课程');
          return;
        }
        res = await request.put(`/api/admin/courses/${currentCourse.id}`, data);
      } else {
        res = await request.post('/api/admin/courses', data);
      }

      if (res.code === 0) {
        message.success(currentCourse ? '更新成功' : '添加成功');
        setModalVisible(false);
        fetchCourses();
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 处理章节内容更新
  const handleScheduleUpdate = async (schedules) => {
    try {
      const res = await request.put(`/api/admin/courses/${currentCourse.id}/schedules`, {
        schedules: schedules.map((schedule, index) => ({
          ...schedule,
          sort: index + 1
        }))
      });

      if (res.code === 0) {
        message.success('章节更新成功');
        fetchSchedules(currentCourse.id);
      }
    } catch (error) {
      message.error('章节更新失败');
    }
  };

  return (
    <Card
      title="课程管理"
      extra={
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            setCurrentCourse(null);
            form.resetFields();
            setFileList([]);
            setModalVisible(true);
          }}
        >
          添加课程
        </Button>
      }
    >
      <Table
        columns={columns}
        dataSource={courses}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1300 }}
        size="default"
        pagination={{
          pageSize: 6,  // 设置每页显示6条
          showTotal: (total) => `共 ${total} 条`,  // 显示总数
          showQuickJumper: true,  // 添加快速跳转
          showSizeChanger: false  // 不显示页码切换器
        }}
      />

      <Modal
        title={currentCourse ? '编辑课程' : '添加课程'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={1200}
        style={{ top: 20 }}
      >
        <Tabs
          items={[
            {
              key: 'basic',
              label: '基本信息',
              children: (
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleSubmit}
                >
                  <Form.Item
                    name="image_url"
                    label={
                      <span>
                        课程封面
                        <span style={{ fontSize: '12px', color: '#999', marginLeft: '8px' }}>
                          (建议尺寸: 800×450)
                        </span>
                      </span>
                    }
                    rules={[{ required: true, message: '请上传课程封面' }]}
                  >
                    <Upload
                      action="/api/admin/upload"
                      listType="picture-card"
                      maxCount={1}
                      data={{
                        type: 'courses'
                      }}
                      fileList={fileList}
                      onChange={({ file, fileList }) => {
                        setFileList(fileList);
                        if (file.status === 'done' && file.response) {
                          if (file.response.code === 0 && file.response.url) {
                            form.setFieldsValue({
                              image_url: file.response.url
                            });
                          } else {
                            message.error('图片上传失败');
                          }
                        }
                      }}
                      onRemove={() => {
                        form.setFieldsValue({ image_url: undefined });
                        setFileList([]);
                      }}
                    >
                      {fileList.length === 0 && (
                        <div>
                          <PlusOutlined />
                          <div style={{ marginTop: 8 }}>上传</div>
                        </div>
                      )}
                    </Upload>
                  </Form.Item>

                  <Form.Item
                    name="title"
                    label="课程名称"
                    rules={[{ required: true, message: '请输入课程名称' }]}
                  >
                    <Input maxLength={100} />
                  </Form.Item>

                  <Form.Item
                    name="category_id"
                    label="课程分类"
                    rules={[{ required: true, message: '请选择课程分类' }]}
                  >
                    <Select>
                      {categories.map(category => (
                        <Option key={category.id} value={category.id}>
                          {category.name}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="tags"
                    label="课程标签"
                  >
                    <Select
                      mode="tags"
                      style={{ width: '100%' }}
                      placeholder="请输入标签"
                    />
                  </Form.Item>

                  <Form.Item
                    name="price"
                    label="课程价格"
                    rules={[{ required: true, message: '请输入课程价格' }]}
                  >
                    <InputNumber
                      min={0}
                      precision={2}
                      style={{ width: '100%' }}
                      prefix="¥"
                    />
                  </Form.Item>

                  <Form.Item
                    name="time_type"
                    label="上课时间"
                    rules={[{ required: true, message: '请选择上课时间' }]}
                  >
                    <Select>
                      {timeTypeOptions.map(option => (
                        <Option key={option.value} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>

                  <Form.Item
                    name="description"
                    label="课程描述"
                  >
                    <TextArea rows={4} maxLength={500} />
                  </Form.Item>
                </Form>
              )
            },
            {
              key: 'schedules',
              label: '课程章节',
              children: currentCourse ? (
                <CourseSchedules
                  schedules={schedules}
                  onUpdate={handleScheduleUpdate}
                />
              ) : (
                <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
                  请先保存课程基本信息
                </div>
              )
            }
          ]}
        />
      </Modal>
    </Card>
  );
};

// 修改课程章节组件
const CourseSchedules = ({ schedules, onUpdate }) => {
  const [editingSchedules, setEditingSchedules] = useState(schedules);

  useEffect(() => {
    setEditingSchedules(schedules);
  }, [schedules]);

  const handleAdd = () => {
    setEditingSchedules([
      ...editingSchedules,
      {
        id: `temp_${Date.now()}`,
        title: '新章节',
        content: '',
        sort: editingSchedules.length + 1
      }
    ]);
  };

  const handleDelete = (index) => {
    const newSchedules = [...editingSchedules];
    newSchedules.splice(index, 1);
    setEditingSchedules(newSchedules);
  };

  const handleChange = (index, field, value) => {
    const newSchedules = [...editingSchedules];
    newSchedules[index][field] = value;
    setEditingSchedules(newSchedules);
  };

  return (
    <div>
      {editingSchedules.map((schedule, index) => (
        <div key={schedule.id} style={{ 
          marginBottom: 20, 
          border: '1px solid #f0f0f0', 
          padding: 16,
          width: '100%'
        }}>
          <Space style={{ 
            marginBottom: 16, 
            width: '100%', 
            justifyContent: 'space-between' 
          }}>
            <Input
              placeholder="章节标题"
              value={schedule.title}
              onChange={(e) => handleChange(index, 'title', e.target.value)}
              style={{ width: '500px' }}
            />
            <Button 
              type="text" 
              danger 
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(index)}
            >
              删除
            </Button>
          </Space>
          <div className="quill-editor-container" style={{ 
            width: '100%',
            marginBottom: 50 
          }}>
            <ReactQuill
              value={schedule.content}
              onChange={(value) => handleChange(index, 'content', value)}
              style={editorStyle}
              modules={{
                toolbar: [
                  ['bold', 'italic', 'underline'],
                  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                  ['clean']
                ]
              }}
              formats={[
                'bold', 'italic', 'underline',
                'list', 'bullet'
              ]}
            />
          </div>
        </div>
      ))}
      <Space style={{ width: '100%', justifyContent: 'center', marginTop: 16 }}>
        <Button type="dashed" onClick={handleAdd} icon={<PlusOutlined />}>
          添加章节
        </Button>
        <Button type="primary" onClick={() => onUpdate(editingSchedules)}>
          保存章节
        </Button>
      </Space>
    </div>
  );
};

export default Courses; 